<template>
  <view class="buy">
    <view class="section1">
      <!-- <navigator url="/pages/address/select" hover-class="none" class="container"> -->
      <view class="container" @click="selectAddress">
        <image
          class="img"
          src="../../static/images/svg/address.svg"
          mode="aspectFill"
        ></image>
        <view class="info" v-if="!userAddress?.id"> 请选择收货地址 </view>
        <view class="info" v-else>
          <view class="title t_line1">{{ userAddress?.allAddress }}</view>
          <view class="text">
            <view class="my-span">{{ userAddress?.name }}</view>
            <view class="my-span">{{ userAddress?.phone }}</view>
            <!-- <view class="my-span t_line1">杭州翰臣科技有限公司</view> -->
          </view>
        </view>
        <image
          class="icon"
          src="../../static/images/svg/arr-right-gray.svg"
          mode="aspectFill"
        ></image>
      </view>

      <!-- </navigator> -->
    </view>
    <view class="section2">
      <view class="container">
        <view class="list my-list1">
          <view
            class="item"
            v-for="(item, index) in orderMes?.carList"
            :key="item.productId"
          >
            <image
              class="line"
              src="/static/images/zwh/zwh14.svg"
              mode="aspectFill"
              v-if="index != 0"
            >
            </image>
            <image
              class="item-img"
              :src="signFun(item?.product?.coverImg)"
              mode="aspectFill"
            ></image>
            <view class="item-info">
              <view class="item-title">
                <view class="my-span t_line1">{{
                  item?.product?.name || '-'
                }}</view>
              </view>
              <view class="des t_line1">{{
                item?.product?.specification || '-'
              }}</view>
              <view class="item-bottom">
                <view class="item-price t_line1">
                  <view class="my-span">￥</view>
                  {{ item?.product.unitPrice || '-' }}
                  <view class="my-span"
                    >￥{{ item?.product?.originalPrice || '-' }}</view
                  >
                </view>
                <view class="item-num">x{{ item?.quantity }}</view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="section3">
      <view class="container">
        <view class="title">支付方式</view>
        <view class="list">
          <view class="item">
            <image
              class="item-icon"
              src="../../static/images/svg/wx.svg"
              mode="aspectFill"
            ></image>
            <view class="item-title t_line1">微信支付</view>
            <image
              class="item-img"
              src="../../static/images/svg/checkbox.svg"
              mode="aspectFill"
            ></image>
          </view>
        </view>
      </view>
    </view>
    <view class="section3">
      <view class="container">
        <view class="item">
          <view class="item-title1">订单备注</view>
          <view class="item-right">
            <input
              class="item-input"
              placeholder-style="color: rgba(255, 255, 255, 0.50);"
              type="text"
              placeholder="备注建议提前协商（250字以内）"
              maxlength="250"
              v-model="text"
            />
          </view>
        </view>
      </view>
    </view>
    <view class="section4 my-safe-bottom">
      <div class="container">
        <view class="price t_line1">
          <view class="price-title"
            >合计
            <view class="my-span">￥</view>
            <view class="my-span2">{{ orderMes?.priceCount }}</view>
          </view>
          <!-- <view class="price-text">共减￥{{save}}</view> -->
        </view>
        <view class="btn" @click="buy">提交订单</view>
      </div>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue'
import { onShow, onLoad } from '@dcloudio/uni-app'
import { getDefaultAddress } from '@/utils/api/address.ts'
import {
  shopcarOrder,
  confirmOrder,
  orderPay,
  yesOrder,
  orderDetail
} from '@/utils/api/order.ts'
import { settlementList } from '@/utils/api/shopping.ts'
import { signFun } from '@/utils/params.ts'
import { productdetails } from '@/utils/api/index.ts'
const selectAddress = () => {
  uni.navigateTo({
    url: '/pagesA/address/select'
  })
}
onMounted(() => {})
onShow(() => {
  getDefaultAddress().then((res: any) => {
    userAddress.value = res.data
  })
})
onLoad((options) => {
  //购物车进入生成订单
  if (options?.carid) {
    carid.value = options?.carid
    settlementList({ carIds: options?.carid }).then((result: any) => {
      orderMes.value = result.data
    })
  } else {
    productdetails({ id: options?.productid }).then((res: any) => {
      if (res.code == 200) {
        orderMes.value = {
          carList: [
            {
              product: { ...res.data },
              productId: options?.productid,
              quantity: options?.quantity
            }
          ],
          priceCount: (
            Number(options?.quantity) * Number(res.data.unitPrice)
          ).toFixed(2)
        }
      }
    })
  }
})
const userAddress = ref(null)
//订单id
const orderid = ref(null)
const carid = ref(null)
const text = ref(null)
const buy = () => {
  if (!userAddress.value.id) {
    uni.showToast({
      title: '请选择收货地址',
      icon: 'none'
    })
    return
  }
  if (carid.value) {
    let arr
    arr = orderMes.value.carList.map((item) => {
      return {
        productCount: item.quantity,
        productId: item.productId
      }
    })
    yesOrder({ carIds: carid.value, saveForms: arr }).then((res: any) => {
      orderid.value = res.data.orderId
      let obj = {
        payType: 1,
        orderId: orderid.value,
        addressId: userAddress.value.id,
        remark: text.value
      }
      orderPay(obj).then((res) => {
        if (res.code == 200) {
          //调用微信官方支付接口弹出付款界面,输入密码扣款
          wx.requestPayment({
            timeStamp: JSON.parse(res.data).timestamp, //时间戳
            nonceStr: JSON.parse(res.data).noncestr, //随机字符串
            package: JSON.parse(res.data).package, //prepay_id
            signType: JSON.parse(res.data).signType, //签名算法MD5
            paySign: JSON.parse(res.data).paySign, //签名
            success(res) {
              if (res.errMsg == 'requestPayment:ok') {
                console.log('支付成功', res)
                uni.reLaunch({
                  url: `/pages/success/success?id=${orderid.value}&price=${orderMes.value.totalPrice}`
                })
              } else {
                setTimeout(() => {
                  uni.showToast({
                    title: '支付失败',
                    icon: 'none'
                  })
                }, 100)
                console.log('支付失败')
              }
            },
            fail(res) {
              setTimeout(() => {
                uni.showToast({
                  title: '支付失败',
                  icon: 'none'
                })
              }, 100)
              console.log('支付失败', res)
            }
          })
        }
      })
    })
  } else {
    let arr
    arr = orderMes.value.carList.map((item) => {
      return {
        productCount: item.quantity,
        productId: item.productId
      }
    })
    yesOrder({ saveForms: arr }).then((res: any) => {
      orderid.value = res.data.orderId
      let obj = {
        payType: 1,
        orderId: orderid.value,
        addressId: userAddress.value.id,
        remark: text.value
      }
      orderPay(obj).then((res) => {
        if (res.code == 200) {
          //调用微信官方支付接口弹出付款界面,输入密码扣款
          wx.requestPayment({
            timeStamp: JSON.parse(res.data).timestamp, //时间戳
            nonceStr: JSON.parse(res.data).noncestr, //随机字符串
            package: JSON.parse(res.data).package, //prepay_id
            signType: JSON.parse(res.data).signType, //签名算法MD5
            paySign: JSON.parse(res.data).paySign, //签名
            success(res) {
              if (res.errMsg == 'requestPayment:ok') {
                console.log('支付成功', res)
                uni.reLaunch({
                  url: `/pages/success/success?id=${orderid.value}&price=${orderMes.value.totalPrice}`
                })
              } else {
                setTimeout(() => {
                  uni.showToast({
                    title: '支付失败',
                    icon: 'none'
                  })
                }, 100)
                console.log('支付失败')
              }
            },
            fail(res) {
              setTimeout(() => {
                uni.showToast({
                  title: '支付失败',
                  icon: 'none'
                })
              }, 100)
              console.log('支付失败', res)
            }
          })
        }
      })
    })
  }
}
const orderMes = ref(null)
const price = ref(null)
const save = ref(null)
</script>

<style>
page {
  background-color: #f7f7f7;
}
</style>
<style lang="scss" scoped>
@import './buy.scss';
</style>
